package com.sxx.mall.ware.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sxx.commons.constant.WareConstant;
import com.sxx.commons.utils.PageUtils;
import com.sxx.commons.utils.Query;
import com.sxx.mall.ware.dao.PurchaseDao;
import com.sxx.mall.ware.entity.PurchaseDetailEntity;
import com.sxx.mall.ware.entity.PurchaseEntity;
import com.sxx.mall.ware.service.PurchaseDetailService;
import com.sxx.mall.ware.service.PurchaseService;
import com.sxx.mall.ware.service.WareSkuService;
import com.sxx.mall.ware.vo.MergeVO;
import com.sxx.mall.ware.vo.PurchaseDoneVO;
import com.sxx.mall.ware.vo.PurchaseItemDoneVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;

@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();


        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils listUnreceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        //查出新建、已分配的订单
        wrapper.eq("status", 0).or().eq("status", 1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }


    @Override
    public Integer merge(MergeVO mergeVO) {
        Long purchaseId = mergeVO.getPurchaseId();
        if (purchaseId == null) {
            //新建采购单
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.purchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        PurchaseEntity purchase = this.getById(purchaseId);
        if (purchase.getStatus() > WareConstant.purchaseDetailStatusEnum.ASSIGNED.getCode()){
            //该采购单不能被合并
            return -1;
        }
        //整合菜单需求单
        List<Long> items = mergeVO.getItems();
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntities = items.stream().map(detailId -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            //根据id更新需要设置对象的id
            purchaseDetailEntity.setId(detailId);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.purchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).filter(id ->{
            PurchaseDetailEntity item = purchaseDetailService.getById(id);
            if (item.getStatus() == WareConstant.purchaseDetailStatusEnum.CREATED.getCode() ||
            item.getStatus() == WareConstant.purchaseDetailStatusEnum.ASSIGNED.getCode()){
                return true;
            }
            return false;
        }).collect(Collectors.toList());
        if (purchaseDetailEntities != null && purchaseDetailEntities.size()>0){
            purchaseDetailService.updateBatchById(purchaseDetailEntities);//根据id更新需要设置对象的id

        }

        // 更新对应的采购单的更新时间
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setUpdateTime(new Date());
        purchaseEntity.setId(purchaseId);
        //TODO ware_id但合并保存的话有多个。。。 ，amount总价计算从detail中拿price相加

        this.updateById(purchaseEntity);

        return 1;
    }

    @Transactional
    @Override
    public void receive(List<Long> ids) {
        // 1.领取的采购单的状态只能是新建或者已分配的采购单 其他的是不能领取的
        List<PurchaseEntity> list = ids.stream().map(id -> {
            return this.getById(id);
        }).filter(item -> {

            if (item.getStatus() == WareConstant.purchaseStatusEnum.CREATED.getCode() ||
                    item.getStatus() == WareConstant.purchaseStatusEnum.ASSIGNED.getCode()) {

                return true;
            }
            return false;
        }).map(item -> {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(item.getId());
            purchaseEntity.setUpdateTime(new Date()); // 设置更新时间
            // 更新采购单的状态为 已领取
            purchaseEntity.setStatus(WareConstant.purchaseStatusEnum.RECEIVED.getCode());
            return purchaseEntity;
        }).collect(Collectors.toList());
        // 2.更新采购单的状态为 已领取
        this.updateBatchById(list);
        // 3.更新采购项的状态为 正在采购
        for (Long id :ids){
            // 根据采购单id 找到对应的采购项对象
            List<PurchaseDetailEntity> detailEntities = purchaseDetailService.listDetailByPurchaseId(id);
            List<PurchaseDetailEntity> collect = detailEntities.stream().map(item -> {
                PurchaseDetailEntity entity = new PurchaseDetailEntity();
                entity.setId(item.getId());
                entity.setStatus(WareConstant.purchaseDetailStatusEnum.PURCHASING.getCode());
                return entity;
            }).collect(Collectors.toList());
            // 批量更新采购项
            purchaseDetailService.updateBatchById(collect);


        }

    }

    @Transactional
    @Override
    public void done(PurchaseDoneVO purchaseDoneVO) {
        //1.改变采购单状态
        Long id = purchaseDoneVO.getId();
        //2.改变采购项状态
        Boolean flag = true; //记录采购状态 默认为 完成
        List<PurchaseItemDoneVO> items = purchaseDoneVO.getItems();
        List<PurchaseDetailEntity> list = new ArrayList<>();
        for (PurchaseItemDoneVO item:items){
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.purchaseDetailStatusEnum.EXCEPTION.getCode()){
                //该采购项出现了问题
                flag = false;
                detailEntity.setStatus(item.getStatus());
            }else {
                //采购项采购成功
                detailEntity.setStatus(WareConstant.purchaseDetailStatusEnum.FINISHED.getCode());
                //3.将采购成功的采购项进入库操作
                //根据采购项编号查询出对应的采购项详情
                PurchaseDetailEntity detailEntity1 = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(detailEntity1.getSkuId(),detailEntity1.getWareId(),detailEntity1.getSkuNum());
            }
            detailEntity.setId(item.getItemId());
            list.add(detailEntity);
        }
        purchaseDetailService.updateBatchById(list);
        //改变采购单状态
        PurchaseEntity purchase = new PurchaseEntity();
        purchase.setId(id);
        purchase.setStatus(flag?WareConstant.purchaseStatusEnum.FINISHED.getCode()
                : WareConstant.purchaseDetailStatusEnum.EXCEPTION.getCode());
        purchase.setUpdateTime(new Date());
        this.updateById(purchase);

    }
}